/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package Xuly;

import java.io.IOException;
import java.io.File;

import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.DocumentBuilder;

import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.Result;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;

import org.xml.sax.SAXParseException;
import org.xml.sax.SAXException;

import org.w3c.dom.Attr;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import com.sun.org.apache.xml.internal.serializer.ElemDesc;

/**
 * 
 * @author CULUN
 */
public class XMLProvider {

	static public void WriteToFile(Document document, String pathOutFile)
			throws TransformerException {

		// Luu vo file
		try {
			// Prepare the DOM document for writing
			Source source = new DOMSource(document);

			// Prepare the output file
			File file = new File(pathOutFile);
			Result result = new StreamResult(file);

			// Write the DOM document to the file
			// Get Transformer
			Transformer xformer = TransformerFactory.newInstance()
					.newTransformer();
			// Write to a file
			xformer.transform(source, result);
		} catch (TransformerConfigurationException e) {
			System.out.println("TransformerConfigurationException: " + e);
		} catch (TransformerException e) {
			System.out.println("TransformerException: " + e);
		}
	}

	static public Document CreateXML(MyDatabase myDatabase) {
		Document document = null;
		DocumentBuilder builder = null;
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		try {
			builder = factory.newDocumentBuilder();
			document = builder.newDocument();

		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		}

		// Them node goc cua tai lieu
		Node databaseNode = document.createElement("database");
		document.appendChild(databaseNode);
		((Element) databaseNode).setAttribute("name", myDatabase.getName());

		// Them cac node table
		ArrayList<MyTable> tables = myDatabase.getTables();
		for (int i = 0; i < tables.size(); i++) {
			// Them node table
			Node tableNode = document.createElement("table");
			databaseNode.appendChild(tableNode);
			((Element) tableNode).setAttribute("name", tables.get(i).getName());

			// Tao cac node column cua 1 table
			ArrayList<MyColumn> columns = tables.get(i).getColumns();
			for (int j = 0; j < columns.size(); j++) {
				// Them node column
				Node columnNode = document.createElement("column");
				tableNode.appendChild(columnNode);
				((Element) columnNode).setAttribute("name", columns.get(j)
						.getName());
				((Element) columnNode).setAttribute("type", columns.get(j)
						.getType());

				// Them node value cho column
				ArrayList<String> values = columns.get(j).getValues();
				for (int k = 0; k < values.size(); k++) {
					Node valueNode = document.createElement("value");
					columnNode.appendChild(columnNode);
					((Element) valueNode).setAttribute("value", values.get(k));
				}
			}
		}
		// Normalizing the DOM
		document.getDocumentElement().normalize();

		return document;
	}

	static public Document ParseXMLFromFile(String pathInFile) {

		// //////////////////////////////////////
		Document document = null;
		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

		factory.setValidating(false);
		factory.setNamespaceAware(true);
		try {
			DocumentBuilder builder = factory.newDocumentBuilder();
			document = builder.parse(new File(pathInFile));
			return document;
		} catch (SAXParseException spe) {
			// Error generated by the parser
			System.out.println("\n** Parsing error , line "
					+ spe.getLineNumber() + ", uri " + spe.getSystemId());
			System.out.println(" " + spe.getMessage());
			// Use the contained exception, if any
			Exception x = spe;
			if (spe.getException() != null) {
				x = spe.getException();
			}
			x.printStackTrace();
		} catch (SAXException sxe) {
			// Error generated during parsing
			Exception x = sxe;
			if (sxe.getException() != null) {
				x = sxe.getException();
			}
			x.printStackTrace();
		} catch (ParserConfigurationException pce) {
			// Parser with specified options can't be built
			pce.printStackTrace();
		} catch (IOException ioe) {
			// I/O error
			ioe.printStackTrace();
		}
		return null;
	}

	static public MyDatabase CreateDatabase(Node node) {
		MyDatabase myDatabase = new MyDatabase();

		// Lay goc tai lieu XML - node database
		Element databaseNode = ((Document) node).getDocumentElement();
		myDatabase.setName(databaseNode.getAttribute("name"));

		// Lay danh sach cac table trong database
		ArrayList<MyTable> tables = new ArrayList<MyTable>();
		NodeList tableNodes = databaseNode.getChildNodes();
		if (tableNodes != null) {
			for (int i = 0; i < tableNodes.getLength(); i++) {
				Node tableNode = tableNodes.item(i);
				// Loai nhung node khong phai element
				if (tableNode.getNodeType() != Node.ELEMENT_NODE)
					continue;

				// Lay danh sach cac column trong table
				NodeList columnNodes = tableNodes.item(i).getChildNodes();
				ArrayList<MyColumn> columns = new ArrayList<MyColumn>();
				if (columnNodes != null) {
					for (int j = 0; j < columnNodes.getLength(); j++) {
						// lay node column
						Element columnNode = (Element) columnNodes.item(j);
						// Loai nhung node khong phai element
						if (columnNode.getNodeType() != Node.ELEMENT_NODE)
							continue;

						// lay danh sach cac value
						NodeList valueNodes = columnNode.getChildNodes();
						ArrayList<String> values = new ArrayList<String>();
						if (valueNodes != null)
							for (int k = 0; k < valueNodes.getLength(); k++) {
								// lay node column
								Element valueNode = (Element) valueNodes
										.item(k);
								// Loai nhung node khong phai element
								if (valueNode.getNodeType() != Node.ELEMENT_NODE)
									continue;
								values.add(valueNode.getAttribute("value"));
							}

						// tao 1 column de them vao database
						MyColumn column = new MyColumn(
								columnNode.getAttribute("name"),
								columnNode.getAttribute("type"), values);
						columns.add(column);
					}
					// tao table de them vao database
					MyTable table = new MyTable(
							((Element) tableNodes.item(i)).getAttribute("name"),
							columns);
					tables.add(table);
				}
			}
		}
		myDatabase.setTables(tables);

		return myDatabase;
	}

}
